package com.gin.no_gay_alliance.viewmodel;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;

/**
 * 用户选中的文件信息
 */
public class FileInfo {
    public static final String TAG = FileInfo.class.getSimpleName();
    /**
     * uri
     */
    public Uri uri;
    /**
     * 大小
     */
    public int size;
    /**
     * 原文件名
     */
    public String originalName;
    /**
     * 后缀
     */
    public String ext;
    /**
     * mimeType
     */
    public String mimeType;
    /**
     * 临时文件
     */
    public File file;

    /**
     * 通过uri读取一个文件的信息
     *
     * @param cr  ContentResolver
     * @param uri uri
     */
    public void read(ContentResolver cr, Uri uri) {
        this.uri = uri;
        try (Cursor cursor = cr.query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                // 开始读取
                originalName = read(cursor, MediaStore.Files.FileColumns.DISPLAY_NAME);
                mimeType = read(cursor, MediaStore.Files.FileColumns.MIME_TYPE);

                String size = read(cursor, MediaStore.Files.FileColumns.SIZE);
                if (size != null) {
                    this.size = Integer.parseInt(size);
                }
                if (originalName != null) {
                    ext = originalName.substring(originalName.lastIndexOf(".") + 1);
                } else if (mimeType != null) {
                    ext = mimeType.split("/")[1];
                }
            } else {
                Log.w(TAG, "读取失败: " + uri);
            }
        }
    }

    private static String read(Cursor cursor, String column) {
        int index = cursor.getColumnIndex(column);
        if (index >= 0) {
            return cursor.getString(index);
        }
        return null;
    }

}